import React from "react";
import { Form, Input, Button, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setUserStore } from "../../store/UserSlice";
import http from "../../utils/http";

const Index = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const onFinish = async (value) => {
    const res = await http.post("/api/login", value);
    const { code, message, data } = res.data;
    if (code === 200) {
      // 登录成功，将token和userInfo保存到本地存储中
      localStorage.setItem("token", data.token);
      localStorage.setItem("userInfo", JSON.stringify(data.userInfo));
      // 保存到redux中
      dispatch(setUserStore(data));
      navigate("/");
    } else {
      Toast.show({
        content: message,
        icon: "fail",
      });
    }
  };

  return (
    <div>
      <Form
        layout="horizontal"
        onFinish={onFinish}
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Header>火车票登陆系统</Form.Header>
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            {
              required: true,
              message: "用户名输入格式不正确",
            //   pattern: /^1[3-9]\d{9}$/,
              //pattern: /\w+@\w+\.\w+/,
            },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[
            {
              required: true,
              message: "密码不能为空",
              // pattern: /^\w{6,12}$/,
              //密码正则：至少包含一个大写字母，一个小写字母和一个数字还有一个特殊字符，长度在6到12之间
              // pattern:
              //   /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w])[\w!@#$%&]{6,12}$/,
            },
          ]}
        >
          <Input placeholder="请输入密码" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
